package com.ym521.myktx

import android.app.Application
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.os.Build
import androidx.annotation.*

/**
 *@author Ym
 *E-mail: 2435970206@qq.com
 *createTime:2024/4/4
 *explain:
 * 获取 values 的资源的辅助类
 */
object Res {

    lateinit var resources: Resources

    /**
     * 建议先在Application 中 调用 init
     */
    fun init(application: Application) {
        resources = application.resources
    }

    fun getColor(@ColorRes colorId: Int, @StyleRes themeId: Int=-1): Int {
        if (!this::resources.isInitialized)
            throw RuntimeException("ResourcesCompat is not Initialized")
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val theme = if (themeId != -1) {
                val theme = resources.newTheme()
                theme.applyStyle(themeId, true)
                theme
            } else {
                null
            }
            resources.getColor(colorId, theme)
        } else {
            resources.getColor(colorId)
        }
    }

    fun getString(@StringRes strId: Int): String {
        if (!this::resources.isInitialized)
            throw RuntimeException("ResourcesCompat is not Initialized")
        return resources.getString(strId)
    }

    fun getDrawable(@DrawableRes drawableId: Int): Drawable {

        return getDrawable(drawableId)
    }

    fun getDrawable(@DrawableRes drawableId: Int, @StyleRes themeId: Int): Drawable {
        if (!this::resources.isInitialized)
            throw RuntimeException("ResourcesCompat is not Initialized")
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val theme = if (themeId != -1) {
                val theme = resources.newTheme()
                theme.applyStyle(themeId, true)
                theme
            } else {
                null
            }
            resources.getDrawable(drawableId, theme)
        }else{
            resources.getDrawable(drawableId)
        }
    }

    /**
     * 通常用于获取那些需要浮点精度的尺寸值，如字体大小或布局间距等。
     */
    fun getDimension(@DimenRes dimenId: Int): Float {
        if (!this::resources.isInitialized)
            throw RuntimeException("ResourcesCompat is not Initialized")
        return resources.getDimension(dimenId)
    }

    /**
     * 通常用于设置视图的宽度或高度。
     */
    fun getDimensionPixel(@DimenRes dimenId: Int): Int {
        if (!this::resources.isInitialized)
            throw RuntimeException("ResourcesCompat is not Initialized")
        return resources.getDimensionPixelSize(dimenId)
    }

}